// ==UserScript==
// @name         智能电商价格监控大师 - 优化性能版
// @namespace    http://tampermonkey.net/
// @version      4.7
// @description 智能价格监控，优化性能不卡顿
// @author       Smart Monitor Pro
// @match        *://*.taobao.com/*
// @match        *://*.tmall.com/*
// @match        *://*.jd.com/*
// @match        *://*.pinduoduo.com/*
// @match        *://*.amazon.cn/*
// @match        *://*.suning.com/*
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_deleteValue
// @grant        GM_listValues
// @grant        GM_notification
// @grant        GM_xmlhttpRequest
// @grant        GM_addStyle
// @require      https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js
// @resource     chartCSS https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.css
// @run-at       document-idle
// ==/UserScript==

(function() {
    'use strict';

    // 配置项
    const CONFIG = {
        checkInterval: 10000, // 10秒检查一次
        priceChangeThreshold: 0.03,
        maxHistoryDays: 180,
        panelPosition: 'left',
        debounceDelay: 2000 // 防抖延迟2秒
    };

    // 主样式
    const STYLES = `
        .smart-price-monitor {
            position: fixed;
            top: 20px;
            left: 20px;
            width: 380px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.15);
            z-index: 10000;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            max-height: 95vh;
            overflow-y: auto;
            font-size: 14px;
            display: none;
        }

        .mini-badge {
            position: fixed;
            top: 20px;
            left: 20px;
            width: 50px;
            height: 50px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 4px 15px rgba(0,0,0,0.3);
            z-index: 10001;
            font-weight: bold;
            font-size: 18px;
        }

        .monitor-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px 15px;
            border-radius: 12px 12px 0 0;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .collapse-btn {
            background: none;
            border: none;
            color: white;
            font-size: 16px;
            cursor: pointer;
            padding: 5px;
        }

        .monitor-tabs {
            display: flex;
            background: #f8f9fa;
            border-bottom: 1px solid #e9ecef;
            padding: 0 10px;
        }

        .tab {
            padding: 10px 15px;
            cursor: pointer;
            border-bottom: 3px solid transparent;
            font-weight: 500;
            flex: 1;
            text-align: center;
        }

        .tab.active {
            border-bottom-color: #667eea;
            color: #667eea;
        }

        .tab-content {
            padding: 15px;
        }

        .instant-deal-section {
            background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
            border: 2px solid #2196f3;
            border-radius: 10px;
            padding: 15px;
            margin: 15px 0;
        }

        .deal-option {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            margin: 8px 0;
            background: white;
            border-radius: 8px;
            border: 1px solid #e0e0e0;
        }

        .deal-option.best {
            background: linear-gradient(135deg, #e8f5e8 0%, #c8e6c9 100%);
            border: 2px solid #4caf50;
        }

        .savings-badge {
            background: #4caf50;
            color: white;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
        }

        .price-comparison {
            background: #fff3e0;
            border: 1px solid #ffb74d;
            border-radius: 8px;
            padding: 12px;
            margin: 10px 0;
        }

        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.2s;
            margin: 5px;
        }

        .btn-primary {
            background: #2196f3;
            color: white;
        }

        .btn-success {
            background: #4caf50;
            color: white;
        }
    `;

    class SmartPriceMonitor {
        constructor() {
            this.products = {};
            this.isProcessing = false;
            this.lastProcessedUrl = '';
            this.lastProcessedTime = 0;
            this.init();
        }

        init() {
            this.addStyles();
            this.createMiniBadge();
            this.loadProducts();
            this.setupEventListeners();
            this.startInstantDealCheck();
            console.log('💰 价格监控脚本已加载 - 性能优化版');
        }

        addStyles() {
            GM_addStyle(STYLES);
        }

        createMiniBadge() {
            this.miniBadge = document.createElement('div');
            this.miniBadge.className = 'mini-badge';
            this.miniBadge.innerHTML = '💰';
            this.miniBadge.title = '点击显示价格监控面板';

            this.miniBadge.addEventListener('click', () => {
                this.togglePanel();
            });

            document.body.appendChild(this.miniBadge);
        }

        createPanel() {
            if (this.panel) return;

            this.panel = document.createElement('div');
            this.panel.className = 'smart-price-monitor';
            this.panel.innerHTML = `
                <div class="monitor-header">
                    <h3 style="margin:0; font-size:16px;">💰 价格监控</h3>
                    <button class="collapse-btn">✕</button>
                </div>
                <div class="monitor-tabs">
                    <div class="tab active" data-tab="instant">即时优惠</div>
                    <div class="tab" data-tab="monitor">商品监控</div>
                </div>
                <div class="tab-content" id="instant-tab">
                    <div class="instant-deal-section">
                        <h4 style="margin:0 0 12px 0;">🎯 当前最优购买方案</h4>
                        <div class="instant-deal-result">正在计算优惠...</div>
                    </div>
                    <div class="price-comparison">
                        <h4 style="margin:0 0 10px 0;">📊 价格信息</h4>
                        <div class="current-price-info">正在获取价格信息...</div>
                    </div>
                </div>
                <div class="tab-content" id="monitor-tab" style="display:none">
                    <div class="monitor-controls">
                        <button class="btn btn-primary" id="add-current-to-monitor">➕ 监控当前商品</button>
                    </div>
                    <div class="monitored-products-list" style="margin-top:15px;"></div>
                </div>
            `;
            document.body.appendChild(this.panel);
            this.setupPanelEvents();
        }

        setupPanelEvents() {
            // 关闭按钮
            this.panel.querySelector('.collapse-btn').addEventListener('click', () => {
                this.togglePanel();
            });

            // 标签切换
            this.panel.querySelectorAll('.tab').forEach(tab => {
                tab.addEventListener('click', () => {
                    this.panel.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                    tab.classList.add('active');

                    this.panel.querySelectorAll('.tab-content').forEach(content => {
                        content.style.display = 'none';
                    });
                    document.getElementById(`${tab.dataset.tab}-tab`).style.display = 'block';

                    if (tab.dataset.tab === 'monitor') {
                        this.updateMonitoredList();
                    }
                });
            });

            // 添加监控按钮
            this.panel.querySelector('#add-current-to-monitor').addEventListener('click', () => {
                this.addCurrentToMonitor();
            });
        }

        togglePanel() {
            if (!this.panel) {
                this.createPanel();
            }

            if (this.panel.style.display === 'none') {
                this.panel.style.display = 'block';
                this.miniBadge.style.display = 'none';
                this.updateInstantDeals();
            } else {
                this.panel.style.display = 'none';
                this.miniBadge.style.display = 'flex';
            }
        }

        setupEventListeners() {
            // 使用防抖技术监听URL变化
            let lastUrl = location.href;
            const observer = new MutationObserver(() => {
                if (location.href !== lastUrl) {
                    lastUrl = location.href;
                    this.debounce(() => {
                        this.updateInstantDeals();
                    }, CONFIG.debounceDelay);
                }
            });

            observer.observe(document, {
                subtree: true,
                childList: true,
                attributes: false,
                characterData: false
            });
        }

        // 防抖函数
        debounce(func, delay) {
            if (this.debounceTimer) {
                clearTimeout(this.debounceTimer);
            }
            this.debounceTimer = setTimeout(func, delay);
        }

        // ==================== 即时优惠计算 ====================

        startInstantDealCheck() {
            // 页面加载完成后延迟执行
            setTimeout(() => {
                this.updateInstantDeals();
            }, 3000);

            // 定期检查（频率降低）
            setInterval(() => {
                if (this.panel && this.panel.style.display !== 'none') {
                    this.updateInstantDeals();
                }
            }, CONFIG.checkInterval);
        }

        async updateInstantDeals() {
            // 防止重复处理
            if (this.isProcessing) return;
            if (Date.now() - this.lastProcessedTime < 2000 &&
                this.lastProcessedUrl === location.href) return;

            this.isProcessing = true;

            try {
                const product = this.getCurrentProductInfo();
                if (!product || !product.price) {
                    this.isProcessing = false;
                    return;
                }

                // 只在面板显示时更新UI
                if (this.panel && this.panel.style.display !== 'none') {
                    const deals = this.calculateInstantDeals(product.price);
                    this.displayInstantDeals(product.price, deals);
                    this.updateCurrentPriceInfo(product);
                }

                this.lastProcessedUrl = location.href;
                this.lastProcessedTime = Date.now();

            } catch (error) {
                console.warn('价格监控处理异常:', error);
            } finally {
                this.isProcessing = false;
            }
        }

        calculateInstantDeals(basePrice) {
            const deals = [{
                name: '原价购买',
                type: 'original',
                discount: 0,
                finalPrice: basePrice,
                description: '不使用任何优惠',
                isBest: false
            }];

            // 简化的优惠计算，避免复杂DOM操作
            try {
                // 查找页面中的优惠信息（简化版）
                const priceElements = document.querySelectorAll([
                    '.price', '.tm-price', '.p-price', '.J-price'
                ].join(', '));

                let foundDiscount = 0;

                // 简单查找折扣文本
                const pageText = document.body.textContent;
                const discountMatch = pageText.match(/(减|立减|优惠|折扣)\s*(\d+)/);
                if (discountMatch) {
                    foundDiscount = parseInt(discountMatch[2]) || 0;
                }

                if (foundDiscount > 0 && foundDiscount < basePrice) {
                    deals.push({
                        name: '页面优惠',
                        type: 'discount',
                        discount: foundDiscount,
                        finalPrice: basePrice - foundDiscount,
                        description: '页面显示的优惠活动',
                        isBest: true
                    });
                }

                // 标记最优方案
                if (deals.length > 1) {
                    deals.sort((a, b) => a.finalPrice - b.finalPrice);
                    deals[0].isBest = true;
                    if (deals[0].finalPrice === basePrice) {
                        deals[0].isBest = false;
                    }
                }

            } catch (e) {
                console.log('优惠计算简化处理');
            }

            return deals;
        }

        displayInstantDeals(originalPrice, deals) {
            if (!this.panel) return;

            const dealResult = this.panel.querySelector('.instant-deal-result');
            if (!dealResult) return;

            const bestDeal = deals.find(deal => deal.isBest);

            let html = deals.map(deal => `
                <div class="deal-option ${deal.isBest ? 'best' : ''}">
                    <div>
                        <strong>${deal.name}</strong>
                        <div style="font-size: 12px; color: #666; margin-top: 4px;">
                            ${deal.description}
                        </div>
                    </div>
                    <div style="text-align: right;">
                        <div style="font-weight: bold; color: ${deal.isBest ? '#4caf50' : '#333'}">
                            ${deal.finalPrice.toFixed(2)}元
                        </div>
                        ${deal.discount > 0 ? `
                            <div style="font-size: 12px; color: #4caf50;">
                                节省 ${deal.discount.toFixed(2)}元
                            </div>
                        ` : ''}
                    </div>
                </div>
            `).join('');

            if (bestDeal && bestDeal.finalPrice < originalPrice) {
                html += `
                    <div style="margin-top: 15px; padding: 12px; background: #e8f5e8; border-radius: 8px;">
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <span style="font-weight: bold;">🎉 最优方案:</span>
                            <span class="savings-badge">
                                节省 ${(originalPrice - bestDeal.finalPrice).toFixed(2)}元
                            </span>
                        </div>
                    </div>
                `;
            }

            dealResult.innerHTML = html;
        }

        updateCurrentPriceInfo(product) {
            const priceInfo = this.panel.querySelector('.current-price-info');
            if (!priceInfo) return;

            priceInfo.innerHTML = `
                <div style="display: flex; justify-content: space-between; margin: 5px 0;">
                    <span>商品价格:</span>
                    <strong>${product.price.toFixed(2)}元</strong>
                </div>
                <div style="display: flex; justify-content: space-between; margin: 5px 0;">
                    <span>平台:</span>
                    <span>${product.platform}</span>
                </div>
                <div style="display: flex; justify-content: space-between; margin: 5px 0;">
                    <span>检测时间:</span>
                    <span>${new Date().toLocaleTimeString()}</span>
                </div>
            `;
        }

        // ==================== 商品监控功能 ====================

        addCurrentToMonitor() {
            const product = this.getCurrentProductInfo();
            if (!product) return;

            if (!this.products[product.id]) {
                this.products[product.id] = {
                    ...product,
                    monitored: true,
                    addedDate: new Date().toISOString(),
                    priceHistory: [{
                        price: product.price,
                        timestamp: Date.now()
                    }]
                };
                GM_setValue('monitored_products', this.products);
                this.showNotification('✅ 已添加到监控列表');
            }
            this.updateMonitoredList();
        }

        updateMonitoredList() {
            if (!this.panel) return;

            const list = this.panel.querySelector('.monitored-products-list');
            if (!list) return;

            list.innerHTML = '<h4>已监控商品</h4>';

            Object.values(this.products).forEach(product => {
                if (product.monitored) {
                    const lastPrice = product.priceHistory?.slice(-1)[0]?.price || product.price;
                    const productElement = document.createElement('div');
                    productElement.className = 'deal-option';
                    productElement.innerHTML = `
                        <div>
                            <strong>${product.title.substring(0, 30)}...</strong>
                            <div style="font-size: 12px; color: #666;">
                                最后价格: ${lastPrice.toFixed(2)}元
                            </div>
                        </div>
                        <button class="remove-btn" data-id="${product.id}">
                            移除
                        </button>
                    `;

                    productElement.querySelector('.remove-btn').addEventListener('click', (e) => {
                        e.stopPropagation();
                        this.removeProduct(product.id);
                    });

                    list.appendChild(productElement);
                }
            });
        }

        removeProduct(productId) {
            if (this.products[productId]) {
                delete this.products[productId];
                GM_setValue('monitored_products', this.products);
                this.updateMonitoredList();
                this.showNotification('🗑️ 已移除监控');
            }
        }

        // ==================== 工具方法 ====================

        getCurrentProductInfo() {
            try {
                const url = window.location.href;
                if (!this.isProductPage(url)) return null;

                const price = this.getCurrentPrice();
                if (!price) return null;

                return {
                    id: this.generateProductId(),
                    url: url,
                    title: this.getProductTitle(),
                    price: price,
                    platform: this.getPlatform()
                };
            } catch (e) {
                console.warn('获取商品信息失败:', e);
                return null;
            }
        }

        getCurrentPrice() {
            // 简化的价格获取逻辑
            try {
                const priceSelectors = [
                    '.price', '.tm-price', '.p-price', '.J-price',
                    '[data-price]', '.price-value'
                ];

                for (const selector of priceSelectors) {
                    const element = document.querySelector(selector);
                    if (element) {
                        const text = element.textContent || '';
                        const priceMatch = text.match(/(\d+\.?\d*)/);
                        if (priceMatch) {
                            return parseFloat(priceMatch[1]);
                        }
                    }
                }

                // 备用方案：查找包含"¥"或"￥"的元素
                const yuanElements = document.querySelectorAll('*');
                for (let i = 0; i < Math.min(yuanElements.length, 100); i++) {
                    const text = yuanElements[i].textContent || '';
                    if (text.includes('¥') || text.includes('￥')) {
                        const priceMatch = text.match(/(\d+\.?\d*)/);
                        if (priceMatch) {
                            return parseFloat(priceMatch[1]);
                        }
                    }
                }

                return null;
            } catch (e) {
                console.warn('价格获取失败:', e);
                return null;
            }
        }

        showNotification(message) {
            console.log('💰', message);
        }

        loadProducts() {
            try {
                this.products = GM_getValue('monitored_products', {});
            } catch (e) {
                this.products = {};
            }
        }

        generateProductId() {
            return Math.random().toString(36).substring(2, 10);
        }

        isProductPage(url) {
            return /item|product|detail|id=/.test(url);
        }

        getPlatform() {
            const host = window.location.hostname;
            if (host.includes('taobao')) return '淘宝';
            if (host.includes('tmall')) return '天猫';
            if (host.includes('jd')) return '京东';
            if (host.includes('pinduoduo')) return '拼多多';
            return '其他平台';
        }

        getProductTitle() {
            return document.title.split('_')[0] || document.querySelector('h1')?.textContent || '未知商品';
        }
    }

    // 延迟初始化，确保页面加载完成
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            setTimeout(() => {
                new SmartPriceMonitor();
            }, 2000);
        });
    } else {
        setTimeout(() => {
            new SmartPriceMonitor();
        }, 2000);
    }

})();